<?php

namespace app\api\controller\shop;

use app\admin\model\shop\Category;
use app\api\model\Pay;
use app\common\controller\Api;
use think\Log;

/**
 * 商户折扣买单接口
 */
class Shopdiscountorder extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['notify'];

    //折扣买单创建订单
    public function orderCreate()
    {
        try {

            $shop_id = input('shop_id',0);

            $pay_price = input('pay_price',0);

            $remark = input('remark','');

            $pay_type = input('pay_type','');

            $collect_money_remark = input('collect_money_remark','');

            $type = input('type',0);

            $collection_code = input('collection_code','');

            $model = new \app\api\model\shop\ShopDiscountOrder();

            $res = $model->add($this->auth->id,$shop_id,$pay_price,$remark,$pay_type,$type,$collect_money_remark,$collection_code);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('',$res);
    }


    //折扣买单预估反的金额
    public function rebate()
    {
        $shop_id = input('shop_id',0);

        $pay_price = input('pay_price',0);

        $order_model = new \app\api\model\shop\ShopDiscountOrder();

        $shop = \app\shopapi\model\Shop::where(['shop_id'=>$shop_id])->field('shop_id,commission_rate,bank_name,bank,bank_num')->find();

        $rebate = $order_model->calculate_rebate($shop['commission_rate'],$pay_price);

        $this->success('',$rebate);
    }


    //折扣买单发起支付
    public function pay()
    {
        try {
            $order_no = input('order_no','');

            if (empty($order_no))$this->error('缺少参数订单编号');

            $order_model = new \app\api\model\shop\ShopDiscountOrder();

            $res = $order_model->pay($order_no);

        }  catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('',$res);
    }

    public function refund()
    {
        $params = input();
        try {
            $model = new \app\api\model\shop\ShopDiscountOrder();
            $params['user_id'] = $this->auth->id;
            $res = $model->refund($params);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('退款成功',$res);
    }

    //回调
    public function notify()
    {
        //$params = input();
        $event_type = input('event_type');
        //if ($event_type=='order.consume.pay'){
        $event = input('event');
        Log::error('折扣买单回调:'.$event);
        $order_model = new \app\api\model\shop\ShopDiscountOrder();

        $res = $order_model->notice_url($event,$event_type);

        $this->success('SUCCESS','SUCCESS');
        //}

    }


}